from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import logging

ID, ASSET, BROKER, CREATE_DATE, START_DATE, START_PRICE, END_DATE, END_PRICE = range (8)

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('PositionTabHandler')
class PositionTabHandler(object):

	def __init__(self, db, view, newButton, deleteButton, parent=None):
		log.debug(" initializing position table view...")
		self.db = db
		self.view = view
		self.parent = parent
		self.handleAssetView(db, newButton, deleteButton, parent)
		
	def handleAssetView(self, db, newButton, deleteButton, parent):
		# setting up model :
		model = QPositionHandlerTableModel(parent, db)
		model.setTable("position")
		# set relations 
		model.setRelation(ASSET, QSqlRelation("asset", "id", "name"))
		model.setRelation(BROKER, QSqlRelation("broker", "id", "name"))
		# set headers
		model.setHeaderData(ID, Qt.Horizontal, "Id")
		model.setHeaderData(ASSET, Qt.Horizontal,"Asset")
		model.setHeaderData(BROKER, Qt.Horizontal,"Broker")
		model.setHeaderData(CREATE_DATE, Qt.Horizontal,"Create date")
		model.setHeaderData(START_DATE, Qt.Horizontal,"Start date")
		model.setHeaderData(START_PRICE, Qt.Horizontal,"Start price")
		model.setHeaderData(END_DATE, Qt.Horizontal,"End date")
		model.setHeaderData(END_PRICE, Qt.Horizontal,"End price")
		model.setSort(ID, Qt.AscendingOrder)
	
		# handling the view association
		view = self.view
		view.setModel(model)
		view.setItemDelegate(QPositionHandlerTableDelegate(view))
		# set hidden columns e.g. id ones :
		view.hideColumn(ID)
		# updating view :
		model.select()
		view.setSelectionMode(QTableView.SingleSelection)
		view.setSelectionBehavior(QTableView.SelectRows)
		self.resizeColumns(None)
	
		# setting up member variables :
		self.model = model
		
		
		# adding signals for add/delete etc...
		if parent is not None:
			parent.connect(newButton, SIGNAL("clicked()"), self.addRecord)
			parent.connect(deleteButton, SIGNAL("clicked()"), self.deleteRecord)
			parent.connect(model, SIGNAL("beforeInsert (QSqlRecord&)"), self.resizeColumns)
			parent.connect(model, SIGNAL("beforeUpdate (int,QSqlRecord&)"), self.resizeColumns)

	
	def addRecord(self):
		row = self.model.rowCount()
		insertedRow = self.model.insertRow(row)
		log.debug(" new row inserted : " + str(insertedRow))
		index = self.model.index(row, ASSET)
		self.view.setCurrentIndex(index)
		self.view.edit(index)
	
	def resizeColumns(self, record):
		log.debug(" resize columns called on record " + str(record))
		self.view.resizeColumnsToContents()
		
	def deleteRecord(self):
		index = self.view.currentIndex()
		log.debug(" called delete record with index valid : " + str(index.isValid()))
		if not index.isValid():
			return
		# removing row
		self.model.removeRow(index.row())
		self.model.submitAll()
		
	def closePosition(self):
		index = self.view.currentIndex()
		log.debug(" called close position with index valid : " + str(index.isValid()))
		if not index.isValid():
			return
		
class QPositionHandlerTableModel(QSqlRelationalTableModel):
	def __init__(self, parent, db):
		super (QPositionHandlerTableModel, self).__init__(parent, db)  
		
		
class QPositionHandlerTableDelegate(QSqlRelationalDelegate):
	def __init__(self, view):
		super (QPositionHandlerTableDelegate, self).__init__(view)  